<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>登录</title>
    <link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="./utils/bootstrap.min.css" />
    <link rel="stylesheet" href="./css/login.min.css" />
    <script src="./utils/jquery-3.5.1.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="loginBox">
        <img src="./img/login/logo.png" alt="" />
        <form>
          <div>
            <input
              id="username"
              type="text"
              class="form-control input-login"
              placeholder="手机号码"
            />
            <div class="invalid-feedback">请输入正确的手机号码</div>
          </div>
          <div>
            <input
              id="password"
              type="password"
              class="form-control input-login"
              placeholder="密码"
            />
            <div class="invalid-feedback">密码错误</div>
          </div>

          <button type="button" class="btn btn-primary" id="loginBtn">
            登录
          </button>
        </form>

        <div class="about-login">
          <a href="#">忘记密码</a>
          <a href="register.html">没有账号？去注册</a>
        </div>
      </div>
    </div>

    <script>
      // 前端预验证
      function isPhone() {
        const username = $("#username").val();
        if (/^1[3456789]\d{9}$/.test(username)) {
          $("#username").toggleClass("is-valid");
          return true;
        } else {
          $("#username").toggleClass("is-invalid");
          return false;
        }
      }

      //点击登录
      $("#loginBtn").click(function () {
        // if (!isPhone()) return alert("手机号码格式不正确");
        const phone = $("#username").val();
        const password = $("#password").val();

        $.ajax({
          // 前后端接口
          url: "/students/login",
          type: "POST",
          data: {
            phone,
            password
          },
          success(res) {
            console.log("后端返回结果：", res);
            if (res.code !== 200) return alert("账号或密码错误，登录失败");
            localStorage.token = res.token;
            alert("恭喜你，登录成功");
            location.href = "home.html";
          }
        });
      });
    </script>
  </body>
</html>
